//
//  SecondViewController.m
//  GOGOTravel
//
//  Created by dllo on 16/1/27.
//  Copyright © 2016年 果果. All rights reserved.
//

#import "SecondViewController.h"
#import "CityHunterViewController.h"
@interface SecondViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewCellDelegate, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UIView *view2;
@property (nonatomic, retain) UIButton *button;
@property (nonatomic, retain) UIButton *button1;
@property (nonatomic, retain) BaseCollectionView *collection;
@property (nonatomic, retain) UISearchBar *searchBar;
@property (nonatomic, retain) NSMutableArray *allCity;
@property (nonatomic, retain) UISearchController *searchController;
@property (nonatomic, retain) UITableView *tabelView;
@property (nonatomic, retain) NSMutableArray *resultArr;
@property (nonatomic, retain) NSString *searchText;
@end

@implementation SecondViewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.searchText = @"";
    }
    return self;
}

- (void)dealloc{
    [_view2 release];
    [_button release];
    [_button1 release];
    [_collection release];
    [_searchBar release];
    [_allCity release];
    [_searchController release];
    [_searchText release];
    [_tabelView release];
    [_resultArr release];
    
    
    [super dealloc];
}


/** 完成跳转页面协议方法 */
- (void)JumpPage:(NSString *)string{
    
   
    [self dismissViewControllerAnimated:YES completion:^{
        self.block(string);
    }];
    
}
/** 视图将要消失 */
- (void)viewWillDisappear:(BOOL)animated{
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor =[UIColor colorWithRed:0.9 green:0.29 blue:0.44 alpha:1];
    [self initSwitchViewButton];
    [self initCollectoin];
    
    [self initButtonDelete];
    [self createSearchBar];
    self.allCity = [NSMutableArray array];

    [self handleData];
    
    
    
}
/**<  数据处理 */
- (void)handleData{
    
    [AFNetWorkingHandle GETRequestWithURLString:@"http://api.breadtrip.com/hunter/products/v2/metadata/?city_name=%E5%A4%A7%E8%BF%9E&sign=f598ec442a3f5cf735e4a671f1e14993&with_citydata=true&with_sortdata=true" completionWithSuccess:^(id result) {
        
        NSDictionary *cityData = result[@"city_data"];
        NSDictionary *oversea_city = cityData[@"oversea_city"];
        NSDictionary *domestic_city = cityData[@"domestic_city"];
        
        NSArray *arr = oversea_city[@"all_city_list"];
        NSArray *arr1 = domestic_city[@"all_city_list"];
       
        for (NSDictionary *dic in arr) {
            NSString *city = dic[@"name"];
            [_allCity addObject:city];
        }
        
        for (NSDictionary *dic in arr1) {
            NSString *city = dic[@"name"];
            [_allCity addObject:city];
        }
        
        NSLog(@"%@", _allCity);
        
        [_tabelView reloadData];
       
    } withFailure:^(id error) {
        NSLog(@"%@", error);
    }];
}

- (void)createSearchBar{
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(-7, 136, WIDTH + 14, 30)];
    _searchBar.barTintColor = UIColorFromRGB(0x099cc);
    _searchBar.placeholder = @"plasece search";
    _searchBar.delegate = self;
    [self.view addSubview:_searchBar];
    [_searchBar release];
}
#pragma mark-searchBar代理方法
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    [_searchBar setShowsCancelButton:YES animated:YES];
    [self createTableView];
    return YES;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [_searchBar resignFirstResponder];
    [_searchBar setShowsCancelButton:NO animated:YES];
    //点击取消移除tableview
    for (UIView *view in self.view.subviews) {
        if ([view isKindOfClass:[UITableView class]]) {
            [view removeFromSuperview];
        }
    }
    
    _searchBar.text = @"";
    
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    self.searchText = searchText;
    
    
    //谓词（包含搜索字符转）
    NSPredicate *pradicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchText];
    
    if (self.resultArr != nil) {
        [_resultArr removeAllObjects];
    }
    //过滤数据
    self.resultArr = [NSMutableArray arrayWithArray:[_allCity filteredArrayUsingPredicate:pradicate]];
    
    [_tabelView reloadData];
    
}
/** 创建展示结果是tableView */
- (void)createTableView{
    
    self.tabelView = [[UITableView alloc] initWithFrame:CGRectMake(0, 170, self.view.frame.size.width, 425) style:UITableViewStylePlain];
    _tabelView.backgroundColor = [UIColor colorWithRed:0.9 green:0.29 blue:0.44 alpha:1];
    _tabelView.delegate = self;
    _tabelView.dataSource = self;
    [self.view addSubview:_tabelView];
    [_tabelView release];
    
    [_tabelView registerClass:[BaseTableViewCell class] forCellReuseIdentifier:@"BaseTableViewCell"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _resultArr.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BaseTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [self dismissViewControllerAnimated:YES completion:^{
        self.block(cell.textLabel.text);
    }];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BaseTableViewCell"];
    NSString *str = _resultArr[indexPath.row];
    
    //初始化
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:str];
   
    //获取关键字的位置
    NSRange range = [str rangeOfString:_searchText];
    
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:20], NSForegroundColorAttributeName:[UIColor redColor]};
    
    //设置关键属性
    [attString setAttributes:dic range:range];
    
    
    
    
    
    cell.textLabel.attributedText = attString;
    
    return cell;
}

/**<  创建开关 */
- (void)initSwitchViewButton{
    
    
    
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(100, 40, 150, 40)];
    view1.backgroundColor = [UIColor colorWithRed:0.9 green:0.29 blue:0.44 alpha:1];
    view1.layer.borderColor = [UIColor whiteColor].CGColor;
    view1.layer.borderWidth = 1;
    view1.layer.cornerRadius = 20;
    view1.layer.masksToBounds = YES;
    [self.view addSubview:view1];
    
    self.view2 = [[UIView alloc] init];
    _view2.frame = CGRectMake(100, 40, 75, 40);
    _view2.backgroundColor = [UIColor whiteColor];
    _view2.layer.borderWidth = 1;
    _view2.layer.borderColor = [UIColor whiteColor].CGColor;
    _view2.layer.cornerRadius = 20;
    _view2.layer.masksToBounds = YES;
    [self.view addSubview:_view2];
    
    self.button = [UIButton buttonWithType:UIButtonTypeCustom];
    _button.frame = CGRectMake(10, 10, 50, 30);
    _button.backgroundColor = [UIColor clearColor];
    _button.center = _view2.center;
    [_button setTitle:@"国内" forState:UIControlStateNormal];
    [_button setTitleColor:UIColorFromRGB(0x099cc) forState:UIControlStateNormal];
    [_button addTarget:self action:@selector(button4Action:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_button];
    
    self.button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    _button1.frame = CGRectMake(189, 45, 50, 30);
    _button1.backgroundColor = [UIColor clearColor];
    [_button1 setTitle:@"国外" forState:UIControlStateNormal];
    [_button1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_button1 addTarget:self action:@selector(button5Action:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_button1];
    
}
/** 地点collectionView */
- (void)initCollectoin{
    
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    layout.itemSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 140);
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    self.collection = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, 140, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 135) collectionViewLayout:layout];
    
    _collection.delegate = self;
    _collection.dataSource = self;
    _collection.backgroundColor = [UIColor colorWithRed:0.9 green:0.29 blue:0.44 alpha:1];
    _collection.pagingEnabled = YES;
    _collection.bounces = NO;
    _collection.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_collection];
    
    [_collection release];
    
    //注册
    [_collection registerClass:[PlaceCollectionViewCell class] forCellWithReuseIdentifier:@"PlaceCollectionViewCell"];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 2;
}
/** collectionview结束减速方法 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (_collection.contentOffset.x == 0) {
        [self button4Action:nil];
    }else{
        [self button5Action:nil];
    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    PlaceCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PlaceCollectionViewCell" forIndexPath:indexPath];
   
    
    cell.delegate = self;
    
    
    //传值到cell里
    //self.cityNameTitle = cell.cityName;
    cell.indexPath = indexPath;
   
    return cell;
}

/** button点击方法 */
- (void)button4Action:(UIButton *)button{
    
    [UIView animateWithDuration:0.5 animations:^{
        _view2.frame = CGRectMake(100, 40, 75, 40);
        [_button1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_button setTitleColor:UIColorFromRGB(0x099cc) forState:UIControlStateNormal];
    }];
    //让collection偏移
    [_collection setContentOffset:CGPointMake(0, 0) animated:YES];
}
- (void)button5Action:(UIButton *)button{
    
    [UIView animateWithDuration:0.5 animations:^{
        
        
        _view2.frame = CGRectMake(175, 40, 75, 40);
        [_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_button1 setTitleColor:UIColorFromRGB(0x099cc) forState:UIControlStateNormal];
    }];
    //让collection偏移
    [_collection setContentOffset:CGPointMake(self.view.frame.size.width, 0) animated:YES];
    
}
/** 设置删除button */
- (void)initButtonDelete{
    
    UIButton *buttonDelete = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonDelete.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 80, [UIScreen mainScreen].bounds.size.height - 40, 40, 40);
    buttonDelete.backgroundColor = [UIColor clearColor];
    [buttonDelete setImage:[UIImage imageNamed:@"iconfont-shanchu.png"] forState:UIControlStateNormal];
    [buttonDelete addTarget:self action:@selector(buttonDeleteAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonDelete];
    
}
/** buttonDelete点击方法 */
- (void)buttonDeleteAction:(UIButton *)button{
  [self dismissViewControllerAnimated:YES completion:^{
      
  }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
